package main

import (
	"context"
	"fmt"
	"golang.org/x/sync/errgroup"
	"io"
	"net/http"
	"os"
	"os/signal"
	"syscall"
)

func main() {
	server := &http.Server{Addr: ":8081"}
	group, ctx := errgroup.WithContext(context.Background())

	group.Go(func() error {
		go func() {
			<-ctx.Done()
			fmt.Println("stop.")
			err := server.Shutdown(ctx)
			if err != nil {
				fmt.Printf("stop err: %v", err)
			}
		}()
		http.HandleFunc("/healthz", func(writer http.ResponseWriter, request *http.Request) {
			_, err := io.WriteString(writer, `{"message": "ok"}`)
			if err != nil {
				fmt.Printf("write string err: %v", err)
			}
		})
		fmt.Println("start...")
		return server.ListenAndServe()
	})

	group.Go(func() error {
		sig := make(chan os.Signal, 2)
		signal.Notify(sig, syscall.SIGQUIT)
		for {
			select {
			case <-ctx.Done():
				fmt.Println("done")
				return ctx.Err()
			case <-sig:
				fmt.Println("sig: ", sig)
				return nil
			}
		}
	})

	err := group.Wait()
	if err != nil {
		fmt.Println("err: ", err)
	}
	fmt.Println("finish!")
}